import { pick, pickValue } from './helper';
import { openAppAsync } from './newsOpenApp';

const NATIVE_REDIRERCT_MAP = {
  LIFE_H5: 0, // 生活H5页面
  NEWS: 16 // 资讯页面
};

const IOS_UNIVERSAL_URL = 'https://openapp.tnaot.com';

function qsStringify(some) {
  if (!some || typeof some !== 'object') return '';
  return Object.keys(some)
    .map(k => `${k}=${encodeURIComponent(some[k])}`)
    .join('&');
}

function getUrlMaker(root) {
  return function getUrl(query) {
    return `${root}?${qsStringify(query)}`;
  };
}

function getPathLang(lang) {
  return /zh/i.test(lang) ? 'zh' : 'km';
}

function getAndroidUrl(lang) {
  return `https://m.tnaot.com/${getPathLang(lang)}/m/download`;
}

function getDefaultJumpData(options) {
  const androidDownloadUrl = getAndroidUrl(options.lang);
  return {
    androidDownloadUrl,
    iosDownloadUrl: androidDownloadUrl
  };
}

function getLanguage(data) {
  const obj = pick(['language', 'lan', 'lang'])(data);
  return Object.keys(obj).reduce((o, k) => ({ lang: o.lang || obj[k] }), {});
}

function excludeUndefined(obj) {
  if (!obj || typeof obj !== 'object') return obj;
  return Object.keys(obj).reduce(
    (o, k) => (obj[k] == undefined ? o : { ...o, [k]: obj[k] }),
    {}
  );
}

function getJumpValidProps(data) {
  return excludeUndefined({
    ...getLanguage(data),
    ...pick([
      'type',
      'nativeRedirect',
      'url',
      'pageType',
      'newsType',
      'newsId',
      'title'
    ])(data)
  });
}

function getJumpDataMaker(urlGetters = {}) {
  const { getIosUrl, getAndroidUrl, getUniversalUrl } = urlGetters;
  const encode = s => encodeURIComponent(s);
  return function getJumpData(options = {}) {
    const validOptions = getJumpValidProps(options);
    const lang = pick('lang')(validOptions);
    const qqAndroidUrl = getUniversalUrl({ lan: lang });
    const androidLink = getAndroidUrl(validOptions);
    const iosLink = getIosUrl(validOptions);
    const iosUniversalLink = getUniversalUrl({
      lan: lang,
      ...validOptions,
      iosLinkUrl: encode(iosLink)
    });
    return {
      lang,
      iosLink,
      androidLink,
      iosUniversalLink,
      qqAndroidUrl,
      ...getDefaultJumpData(validOptions)
    };
  };
}

function makeOpenApp({ androidRoot, iosRoot, iosUniversalRoot }) {
  const getJumpData = getJumpDataMaker({
    getIosUrl: getUrlMaker(iosRoot),
    getAndroidUrl: getUrlMaker(androidRoot),
    getUniversalUrl: getUrlMaker(iosUniversalRoot)
  });

  return function openApp(options = {}) {
    const data = getJumpData(options);
    if (options.downloadAppWhenFailed === false) {
      delete data.androidDownloadUrl;
      delete data.iosDownloadUrl;
    }
    return openAppAsync(data);
  };
}

// 唤起APP，打开原生页面
const openAppNativePage = makeOpenApp({
  iosRoot: 'com.khmer.todaynews://news/message',
  androidRoot: 'tnaot://news/message',
  iosUniversalRoot: IOS_UNIVERSAL_URL
});

// 唤起APP，打开资讯页面、webview等非原生页面
const openAppPage = makeOpenApp({
  iosRoot: 'com.khmer.todaynews://news/share',
  androidRoot: 'tnaot://news/share',
  iosUniversalRoot: IOS_UNIVERSAL_URL
});

// 唤起APP
function jump(options = {}) {
  const nonNativeCodes = pickValue(['LIFE_H5', 'NEWS'])(NATIVE_REDIRERCT_MAP);
  const nativeRedirect = pick('nativeRedirect')(options);
  const eq = (a, b) => `${a}` === `${b}`;
  if (nonNativeCodes.some(c => eq(c, nativeRedirect))) {
    return openAppPage(options);
  }
  return openAppNativePage(options);
}

export default jump;
